package com.jiuyin.dianjing.ui.activity.community;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.MotionEvent;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.jiuyin.dianjing.R;
import com.jiuyin.dianjing.api.base.DefaultApiResult;
import com.jiuyin.dianjing.api.enums.ApiEnum;
import com.jiuyin.dianjing.api.interfaces.ApiResultCallback;
import com.jiuyin.dianjing.api.server.ServerApi;
import com.jiuyin.dianjing.app.HelperApplication;
import com.jiuyin.dianjing.model.UniversityClub;
import com.jiuyin.dianjing.ui.activity.base.BaseActivity;
import com.jiuyin.dianjing.ui.fragment.community.CollegesListFragment;
import com.jiuyin.dianjing.util.IMEUtil;
import com.jiuyin.dianjing.util.ToastUtil;

import org.json.JSONObject;

import java.util.HashMap;

import butterknife.BindView;

import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_PAGE_NUM;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_TOKEN;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_WORD;
import static com.jiuyin.dianjing.api.constant.ApiConstant.PAGE_FIRST;
import static com.jiuyin.dianjing.app.HelperApplication.getContext;

public class CollegesListActivity extends BaseActivity {
    public static final int REQUEST_APPLY = 75;
    @BindView(R.id.et_search)
    EditText mSearchView;
    @BindView(R.id.iv_background)
    ImageView ivBg;
    @BindView(R.id.tv_name)
    TextView tvName;
    private String status = "3";

    private CollegesListFragment collegesListFragment;
    private int mPageNum = PAGE_FIRST;
    private UniversityClub club;

    @Override
    protected int setLayoutId() {
        return R.layout.activity_colleges_list;
    }

    @Override
    protected void initData() {
        fetchData();
    }

    private void fetchData() {
        HashMap<String, Object> data = new HashMap<>();
        data.put(KEY_TOKEN, HelperApplication.getToken());
        data.put(KEY_WORD, "");
        data.put(KEY_PAGE_NUM, mPageNum);
        JSONObject jsonObject = new JSONObject(data);
        ApiResultCallback requestCallback = new DefaultApiResult() {
            @Override
            public void onSuccess(JsonObject data) {
                status = String.valueOf(data.get("status"));
                club = new UniversityClub();
                if (status.equals("0")) {
                    tvName.setText("电竞社申请中");
                } else if (status.equals("1")) {
                    if (data.has("universityClub")) {
                        club = new Gson().fromJson(data.get("universityClub"), UniversityClub.class);
                        tvName.setText(club.name);
                        Glide.with(getContext())
                                .load(club.list_logo)
                                .override(ivBg.getWidth(), ivBg.getHeight())
                                .into(ivBg);
                    }
                } else {
                    tvName.setText("申请高校电竞社");
                }
            }

            @Override
            public void onError(String msg) {
                super.onError(msg);
            }

            @Override
            public void onFail(String msg) {
                super.onFail(msg);
            }
        };
        ServerApi.post(ApiEnum.GET_UNIVERSITY_CLUB_LIST, jsonObject, null, progress, d -> addDisposable(d), requestCallback);
    }

    @SuppressLint("ClickableViewAccessibility")
    @Override
    protected void initView() {
        setTitle("高校电竞社");
        collegesListFragment = CollegesListFragment.newInstance();
        getSupportFragmentManager().beginTransaction()
                .replace(R.id.layout_fragment, collegesListFragment)
                .commit();
        ivBg.setOnClickListener(v -> {
            if (status.equals("0")) {
                ToastUtil.showShort("电竞社申请中");
            } else if (status.equals("1")) {
                Intent intent = new Intent(CollegesListActivity.this, CollegeMainActivity.class);
                intent.putExtra("UniversityClub", club);
                startActivity(intent);
            } else {
                Intent intent = new Intent(CollegesListActivity.this, CollegeApplyActivity.class);
                startActivityForResult(intent, REQUEST_APPLY);
            }
        });
        mSearchView.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                collegesListFragment.setWord(mSearchView.getText().toString());
                collegesListFragment.refresh();
            }
        });
        mSearchView.setOnEditorActionListener((v, actionId, event) -> {
            String content = v.getText().toString().trim();
            if (!TextUtils.isEmpty(content)) {
                collegesListFragment.setWord(mSearchView.getText().toString());
                collegesListFragment.refresh();
            }
            IMEUtil.hideInputMethod(CollegesListActivity.this);
            return true;
        });
        mSearchView.setOnTouchListener((v, event) -> {
            Drawable drawable = mSearchView.getCompoundDrawables()[2];
            if (drawable == null) {
                return false;
            }
            if (event.getAction() != MotionEvent.ACTION_UP) {
                return false;

            }
            if (TextUtils.isEmpty(mSearchView.getText().toString())) {
                return false;
            }
            if (event.getX() > mSearchView.getWidth()
                    - mSearchView.getPaddingRight()
                    - drawable.getIntrinsicWidth()) {
                mSearchView.setText("");
            }
            return false;
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if (requestCode == REQUEST_APPLY && resultCode == RESULT_OK) {
            initData();
            return;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

}
